package org.biubiu0002.baiblog.core.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.biubiu0002.baiblog.common.exception.BizCodeEnumException;
import org.biubiu0002.baiblog.common.utils.R;
import org.biubiu0002.baiblog.core.model.dto.TokenUserDto;
import org.biubiu0002.baiblog.core.service.AuthService;
import org.biubiu0002.baiblog.core.utils.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: biubiu0002
 * @Date: 2022-05-07 22:06
 * 认证登录拦截器
 **/
@Component
@Slf4j
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private AuthService authService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();


    private Set<String> whiteList;

    @PostConstruct
    public void init(){
        whiteList= new HashSet<>();
        whiteList.add("/auth/**");
        whiteList.add("/oauth/**");
        whiteList.add("/share/**");
        whiteList.add("/oss/policy");
        whiteList.add("/sysuser/**");
        whiteList.add("/friendship/**");
        whiteList.add("/test/**");
//        whiteList.add("/sysrole/**");
//        whiteList.add("/syspermission/**");
//        whiteList.add("/auth");
//        whiteList.add("/auth/login");
//        whiteList.add("/auth/register");
//        whiteList.add("/auth/logout");
//        whiteList.add("/share/list");
//        whiteList.add("/share/likeBoard");
//        whiteList.add("/share/");

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //根据token获取登录用户信息并保存到缓存
        String token = request.getHeader("token");
        TokenUserDto tokenUser = authService.getTokenUser(token);
        request.setAttribute("user",tokenUser);
        SecurityUtils.setUser(tokenUser);

        if(tokenUser!=null){
            return true;
        }
        //没有登陆 再看是否能进入白名单url
        String uri = request.getRequestURI();
        for(String s:whiteList){
            if (antPathMatcher.match(s,uri)) {
                return true;
            }
        }

        response.setContentType("application/json;charset=utf-8");
        R r = R.error(BizCodeEnumException.NOT_LOGIN_EXCEPTION);
        PrintWriter pw = response.getWriter();
        pw.write(JSON.toJSONString(r));
        pw.flush();
        pw.close();
        return false;
    }

    /**
     *  后置处理清除threadLocal 用户缓存
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityUtils.removeUser();
    }
}
